package com.navinfo.gateway.platform.server.netty.initializer;


import com.navinfo.gateway.platform.server.netty.codec.TcpDecoder;
import com.navinfo.gateway.platform.server.netty.codec.TcpEncoder;
import com.navinfo.gateway.platform.server.netty.handler.TerminalDispatchTcpHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 初始化通道
 *
 * @author zhengshibo
 * @date 2018-03-14
 */
@Component
public final class TerminalChannelInitializer extends ChannelInitializer<Channel> {

    @Value("${tcp.heartbeat.time:120}")
    private int heartbeat;

    @Autowired
    private TerminalDispatchTcpHandler terminalDispatchTcpHandler;

    @Override
    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        //配置服务端监听读超时，即无法收到客户端发的心跳信息的最长时间间隔：默认2分钟
        pipeline.addLast("ping", new IdleStateHandler(heartbeat, 0, 0, TimeUnit.SECONDS));
        pipeline.addLast("JT808Decoder", new TcpDecoder());
        pipeline.addLast("JT808Encoder", new TcpEncoder());
        pipeline.addLast("handle", terminalDispatchTcpHandler);
    }
}
